/**
 * Captain
 * © 2017 Captain copyright，All rights reserved.
 * http://www.sccaptain.com.cn
 * 
 * JAVA : 8
 * 文  件  名: CasServiceAuthenticationDetailsSource.java
 * 创  建  人: Roc Zheng (roc.djz@gmail.com)
 * 创建时间: 2017年8月23日 上午11:27:44
 * 版         本: 1.0.0
 * 备         注:
 * 修订历史:
 */
package com.material.c2c.web.sys.security;

import java.net.MalformedURLException;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails;

import com.cpt.framework.core.SystemRuntimeException;

/**
 * 
 * 
 * @since 1.0
 * @version 1.0
 * @author Roc Zheng (roc.djz@gmail.com)
 */
public class CasServiceAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, ServiceAuthenticationDetails> {
  private final Pattern artifactPattern;
  private ServiceProperties serviceProperties;
  
  /**
   * Creates an implementation that uses the specified ServiceProperites and the default
   * CAS artifactParameterName.
   *
   * @param serviceProperties The ServiceProperties to use to construct the serviceUrl.
   */
  public CasServiceAuthenticationDetailsSource(ServiceProperties serviceProperties) {
    this(serviceProperties, ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER);
  }

  /**
   * Creates an implementation that uses the specified artifactParameterName
   *
   * @param serviceProperties The ServiceProperties to use to construct the serviceUrl.
   * @param artifactParameterName the artifactParameterName that is removed from the
   * current URL. The result becomes the service url. Cannot be null and cannot be an
   * empty String.
   */
  public CasServiceAuthenticationDetailsSource(ServiceProperties serviceProperties, String artifactParameterName) {
    this.serviceProperties = serviceProperties;
    this.artifactPattern = CasServiceAuthenticationDetails.createArtifactPattern(artifactParameterName);
  }
  
  /**
   * @param context the {@code HttpServletRequest} object.
   * @return the {@code ServiceAuthenticationDetails} containing information about the
   * current request
   */
  public ServiceAuthenticationDetails buildDetails(HttpServletRequest context) {
    try {
      return new CasServiceAuthenticationDetails(serviceProperties.getService(), context, artifactPattern);
    }
    catch (MalformedURLException e) {
      throw new SystemRuntimeException(e);
    }
  }
}
